package cn.com.huzo.service.trade.impl;

import cn.com.huzo.model.entities.trade.ProductionInstructionLinesColourOrderEntity;
import cn.com.huzo.model.entities.trade.ProductionInstructionLinesDestinationEntity;
import cn.com.huzo.model.entities.trade.ProductionInstructionLinesDestinationSchemaEntity;
import cn.com.huzo.model.entities.trade.ProductionInstructionLinesEntity;
import cn.com.huzo.model.entities.trade.ProductionInstructionLinesSuitSizeEntity;
import cn.com.huzo.repository.trade.ProductionInstructionLinesDestinationRepository;
import cn.com.huzo.repository.trade.ProductionInstructionLinesDestinationSchemaRepository;
import huzofw.service.impl.GenericManagerImpl;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.com.huzo.repository.trade.ProductionInstructionLinesRepository;
import cn.com.huzo.repository.trade.ProductionInstructionLinesSuitSizeRepository;
import cn.com.huzo.service.trade.ProductionInstructionLinesManager;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import org.apache.commons.collections4.MapUtils;

/**
 * 生产指示书明细管理服务对象类实现。
 *
 * @author 吴旭
 */
@Service("ProductionInstructionLinesManager")
public class ProductionInstructionLinesManagerImpl extends GenericManagerImpl<ProductionInstructionLinesEntity, String>
        implements ProductionInstructionLinesManager {

    @Resource(name = "ProductionInstructionLinesRepository")
    private ProductionInstructionLinesRepository _dao_lines;

    @Resource(name = "ProductionInstructionLinesSuitSizeRepository")
    private ProductionInstructionLinesSuitSizeRepository _dao_lines_suitsize;

    @Resource(name = "ProductionInstructionLinesDestinationRepository")
    private ProductionInstructionLinesDestinationRepository _dao_lines_destination;

    @Resource(name = "ProductionInstructionLinesDestinationSchemaRepository")
    private ProductionInstructionLinesDestinationSchemaRepository _dao_lines_schema;

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    @Transactional
    public Map<String, Object> fetchLinesByHeaderId(Long headerId) throws Exception {
        Map<String, Object> _result = new HashMap();

        _result.put("ScheduleNode", _dao_lines_schema.fetchScheduleDateNode(headerId));
        _result.put("LinesList", _dao_lines.fetchLinesByHeaderIdAndStyleNo(headerId, null));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> batchInsert(Map<String, Object> criterion) throws Exception {
        // 分解上传数据
        ObjectMapper mapper = new ObjectMapper();
        List<ProductionInstructionLinesEntity> itemList = mapper.convertValue(MapUtils.getObject(criterion, "LinesList"), new TypeReference<List<ProductionInstructionLinesEntity>>() {
        });

        for (int i = 0; i < itemList.size(); i++) {
            ProductionInstructionLinesEntity instance = itemList.get(i);
            // step1: 插入明细并获得明细标识
            String linesId = _dao_lines.insert(instance);
            if (linesId != null && !linesId.isEmpty()) {
                // step2: 插入套装尺码明细
                List<ProductionInstructionLinesSuitSizeEntity> _suitSizeList = instance.getSuiteSizeMemo();
                for (int j = 0; j < _suitSizeList.size(); j++) {
                    ProductionInstructionLinesSuitSizeEntity suitSizeEntity = (ProductionInstructionLinesSuitSizeEntity) _suitSizeList.get(j);
                    suitSizeEntity.setHeaderId(instance.getHeaderId());
                    suitSizeEntity.setParentLinesId(linesId);
                    _dao_lines_suitsize.insert(suitSizeEntity);
                }
                // step3: 插入发货目的地
                List<ProductionInstructionLinesDestinationEntity> _destinationList = instance.getDestinationMemo();
                for (int l = 0; l < _destinationList.size(); l++) {
                    ProductionInstructionLinesDestinationEntity destinationEntity = (ProductionInstructionLinesDestinationEntity) _destinationList.get(l);
                    destinationEntity.setHeaderId(instance.getHeaderId());
                    destinationEntity.setDestination(destinationEntity.getDestination());
                    destinationEntity.setCreatedBy(destinationEntity.getCreatedBy());
                    destinationEntity.setUpdatedBy(destinationEntity.getUpdatedBy());
                    _dao_lines_destination.insert(destinationEntity);
                }
                // step4: 插入生产数量分配明细
                //JSONArray schemaArr = JSONArray.fromObject(instance.getSchemaMemo());
                List<ProductionInstructionLinesDestinationSchemaEntity> schemaArr = instance.getSchemaMemo();
                for (int k = 0; k < schemaArr.size(); k++) {
                    ProductionInstructionLinesDestinationSchemaEntity _item = schemaArr.get(k);

                    ProductionInstructionLinesDestinationSchemaEntity schemaEntity = new ProductionInstructionLinesDestinationSchemaEntity();
                    schemaEntity.setHeaderId(instance.getHeaderId());
                    schemaEntity.setParentLinesId(linesId);
                    schemaEntity.setDestination(_item.getDestination());
                    schemaEntity.setDeliveryDate(_item.getDeliveryDate());
                    schemaEntity.setQuantity(_item.getQuantity());

                    _dao_lines_schema.insert(schemaEntity);
                }
            }
        }
        // 插入颜色对应的顺序表
        Integer rowsAffected = _dao_lines.insertLinesColourOrder((List<Map<String, Object>>) MapUtils.getObject(criterion, "LinesColourOrder"));

        // 审计日志
        if (rowsAffected > 0) {
            writeAuditLog(itemList.get(0).getUpdatedBy(), "贸易信息→生产指示书明细",
                    "款号：" + itemList.get(0).getSuitStyleNo(),
                    "增加明细");
        }

        // 返回值
        Map<String, Object> _result = new HashMap();
        _result.put("ScheduleNode", _dao_lines_schema.fetchScheduleDateNode(itemList.get(0).getHeaderId()));
        _result.put("DestinationNode", _dao_lines_destination.fetchProductionInstructionLinesDestinationNode(itemList.get(0).getHeaderId()));
        _result.put("LinesList", _dao_lines.fetchLinesByHeaderIdAndStyleNo(itemList.get(0).getHeaderId(), null));
        _result.put("SumQuantity", _dao_lines.fetchTotalQuantityByHeaderId(itemList.get(0).getHeaderId()));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> insertLinesByNewColour(Long headerId, Long colourId) throws Exception {
        Map<String, Object> _result = new HashMap();

        Integer rowsAffected = _dao_lines_suitsize.insertForNewColourLines(headerId);
        if (rowsAffected > 0) {
            _dao_lines.insertLinesByNewColour(headerId, colourId);
            _dao_lines_suitsize.updateParentLinesIdForNewColourLines(headerId);
            // 新增颜色的顺序设置
            _dao_lines.insertColourOrderLinesByNewColour(headerId);
            // 增加对应新增明细行的分配数据
            _dao_lines_schema.insertByNewLines(headerId);

            _result.put("LinesList", _dao_lines.fetchLinesByHeaderIdAndStyleNo(headerId, null));
            _result.put("Success", true);
        } else {
            _result.put("Success", false);
        }

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> batchUpdate(List<ProductionInstructionLinesEntity> itemList) throws Exception {
        Integer rowsAffected = _dao_lines.updateLines(itemList);
        if (rowsAffected > 0) {
            for (ProductionInstructionLinesEntity instance : itemList) {
                // 删除属于该明细的生产数据分配明细
                //_dao_lines_schema.deleteByParentLinesId(instance.getLinesId());
                // 插入生产数量分配明细
                List<ProductionInstructionLinesDestinationSchemaEntity> _schemaList = instance.getSchemaMemo();
                for (ProductionInstructionLinesDestinationSchemaEntity entity : _schemaList) {
                    _dao_lines_schema.update(entity);
                    rowsAffected = rowsAffected + 1;
                }
            }
            // 审计日志
            writeAuditLog(itemList.get(0).getUpdatedBy(), "贸易信息→生产指示书明细",
                    "款号：" + itemList.get(0).getSuitStyleNo(),
                    "更新明细");
        }

        Map<String, Object> _result = new HashMap();
        _result.put("ScheduleNode", _dao_lines_schema.fetchScheduleDateNode(itemList.get(0).getHeaderId()));
        _result.put("DestinationNode", _dao_lines_destination.fetchProductionInstructionLinesDestinationNode(itemList.get(0).getHeaderId()));
        _result.put("LinesList", _dao_lines.fetchLinesByHeaderIdAndStyleNo(itemList.get(0).getHeaderId(), null));
        _result.put("SumQuantity", _dao_lines.fetchTotalQuantityByHeaderId(itemList.get(0).getHeaderId()));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> updateLinesColour(List<ProductionInstructionLinesEntity> itemList) throws Exception {
        Integer rowsAffected = _dao_lines.updateLinesColour(itemList);
        if (rowsAffected > 0) {
            // 同步颜色顺序表
            _dao_lines.syncDeleteLinesColourOrder(itemList.get(0).getHeaderId());
            // 新增颜色的顺序设置
            _dao_lines.insertColourOrderLinesByNewColour(itemList.get(0).getHeaderId());
            // 审计日志
            writeAuditLog(itemList.get(0).getUpdatedBy(), "贸易信息→生产指示书明细",
                    "款号：" + itemList.get(0).getSuitStyleNo() + " 颜色：（" + itemList.get(0).getColourNumber() + "）" + itemList.get(0).getColourName(),
                    "更新颜色");
        }

        Map<String, Object> _result = new HashMap();
        _result.put("ScheduleNode", _dao_lines_schema.fetchScheduleDateNode(itemList.get(0).getHeaderId()));
        _result.put("DestinationNode", _dao_lines_destination.fetchProductionInstructionLinesDestinationNode(itemList.get(0).getHeaderId()));
        _result.put("LinesList", _dao_lines.fetchLinesByHeaderIdAndStyleNo(itemList.get(0).getHeaderId(), null));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> updateLinesShippingMarkNo(List<ProductionInstructionLinesEntity> itemList) throws Exception {
        Integer rowsAffected = _dao_lines.updateLinesShippingMarkNo(itemList);

        if (rowsAffected > 0) {
            // 审计日志
            writeAuditLog(itemList.get(0).getUpdatedBy(), "贸易信息→生产指示书明细",
                    "款号：" + itemList.get(0).getSuitStyleNo() + " 唛头号:" + itemList.get(0).getShippingMarkNo(),
                    "更新唛头号");
        }

        Map<String, Object> _result = new HashMap();
        _result.put("ScheduleNode", _dao_lines_schema.fetchScheduleDateNode(itemList.get(0).getHeaderId()));
        _result.put("DestinationNode", _dao_lines_destination.fetchProductionInstructionLinesDestinationNode(itemList.get(0).getHeaderId()));
        _result.put("LinesList", _dao_lines.fetchLinesByHeaderIdAndStyleNo(itemList.get(0).getHeaderId(), null));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public List<Map<String, Object>> fetchProductColourFromMoByHeaderId(Long headerId) throws Exception {
        return _dao_lines.fetchProductColourFromMoByHeaderId(headerId);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public List<Map<String, Object>> fetchProductColourFromMoByProductId(Long productId) throws Exception {
        return _dao_lines.fetchProductColourFromMoByProductId(productId);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public List<Map<String, Object>> fetchProductSizeFromMoByProductId(Long productId) throws Exception {
        return _dao_lines.fetchProductSizeFromMoByProductId(productId);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> delete(Map<String, Object> criterion) throws Exception {
        Integer rowsAffected = _dao_lines.delete(MapUtils.getString(criterion, "LinesId"));
        if (rowsAffected > 0) {
            // 删除对应的颜色顺序表
            _dao_lines.deleteLinesColourOrder(MapUtils.getLong(criterion, "HeaderId"));
            _dao_lines_destination.deleteInvalidData(MapUtils.getLong(criterion, "HeaderId"));

            // 审计日志
            writeAuditLog(MapUtils.getLong(criterion, "DeletedBy"), "贸易信息→生产指示书明细",
                    "明细信息：" + MapUtils.getString(criterion, "DeletedLinesInfo"),
                    "删除");
        }
        Map<String, Object> _result = new HashMap();
        _result.put("ScheduleNode", _dao_lines_schema.fetchScheduleDateNode(MapUtils.getLong(criterion, "HeaderId")));
        _result.put("DestinationNode", _dao_lines_destination.fetchProductionInstructionLinesDestinationNode(MapUtils.getLong(criterion, "HeaderId")));
        _result.put("LinesList", _dao_lines.fetchLinesByHeaderIdAndStyleNo(MapUtils.getLong(criterion, "HeaderId"), null));
        _result.put("SumQuantity", _dao_lines.fetchTotalQuantityByHeaderId(MapUtils.getLong(criterion, "HeaderId")));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> batchDelete(List<ProductionInstructionLinesEntity> itemList) throws Exception {
        for (int i = 0; i < itemList.size(); i++) {
            ProductionInstructionLinesEntity instance = itemList.get(i);
            Integer rowsAffected = _dao_lines.delete(instance.getLinesId());
            if (rowsAffected > 0) {
                // 删除对应的颜色顺序表
                _dao_lines.deleteLinesColourOrder(instance.getHeaderId());
                _dao_lines_destination.deleteInvalidData(instance.getHeaderId());
            }
        }

        Map<String, Object> _result = new HashMap();
        _result.put("ScheduleNode", _dao_lines_schema.fetchScheduleDateNode(itemList.get(0).getHeaderId()));
        _result.put("DestinationNode", _dao_lines_destination.fetchProductionInstructionLinesDestinationNode(itemList.get(0).getHeaderId()));
        _result.put("LinesList", _dao_lines.fetchLinesByHeaderIdAndStyleNo(itemList.get(0).getHeaderId(), null));
        _result.put("SumQuantity", _dao_lines.fetchTotalQuantityByHeaderId(itemList.get(0).getHeaderId()));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    public List<ProductionInstructionLinesColourOrderEntity> fetchLinesColourOrderByHeaderId(Long headerId) throws Exception {
        return _dao_lines.fetchLinesColourOrderByHeaderId(headerId);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> updateLinesColourOrder(List<Map<String, Object>> itemList) throws Exception {
        _dao_lines.updateLinesColourOrder(itemList);
        // 返回值
        Map<String, Object> _result = new HashMap();
        _result.put("ScheduleNode", _dao_lines_schema.fetchScheduleDateNode(MapUtils.getLong(itemList.get(0), "HeaderId")));
        _result.put("DestinationNode", _dao_lines_destination.fetchProductionInstructionLinesDestinationNode(MapUtils.getLong(itemList.get(0), "HeaderId")));
        _result.put("LinesList", _dao_lines.fetchLinesByHeaderIdAndStyleNo(MapUtils.getLong(itemList.get(0), "HeaderId"), null));

        return _result;
    }
}
